export default {
	state:{
		list:[
			
		],
		selectedList:[]
	},
	getters:{
		// 判断是否全选
		checkedAll(state) {
			return state.list.length === state.selectedList.length;
		},
		// 合计和计算数量
		totalCount(state) {
			let total = {
				pprice:0,
				num:0
			}
			state.list.forEach(v=>{
				// 判断是否有商品被选中
				if(state.selectedList.indexOf(v.id) >-1){
					//合计
					total.pprice += v.pprice*v.num;
					//计算数量
					total.num = state.selectedList.length;
				}
			})
			return total;
		}
	},
	mutations:{
		//全选方法
		checkAll(state){
			state.selectedList = state.list.map(v=> {
				v.checked = true;
				return v.id;
			})
		},
		// 全不选方法
		unCheckAll(state){
			state.list.forEach(v=>{
				v.checked = false;
			})
			state.selectedList = [];
		},
		// 控制单选按钮
		selectedItem(state,index) {
			let id = state.list[index].id;
			// console.log(id);
			let i = state.selectedList.indexOf(id);
			// 存在对应id值，代表之前是选中状态，那么要中数组中移除
			if( i > -1){
				state.list[index].checked = false;
				return state.selectedList.splice(i,1);
			}
			// 如果之前没有选中，那么要将当前的id添加到selectedList中，并且设置为true
			state.list[index].checked = true;
			state.selectedList.push(id);
		},
		//删除商品
		delGoods(state) {
			state.list = state.list.filter(v=>{
				return state.selectedList.indexOf(v.id)  == -1;
			})
		},
		//加入购物车
		addShopCart(state,goods){
			state.list.push(goods);
		}
	},
	actions:{
		checkedAllFn({commit,getters}) {
			getters.checkedAll ? commit("unCheckAll"):commit("checkAll");
		},
		delGoodsFn({commit}) {
			commit('delGoods');
			commit('unCheckAll');
			uni.showToast({
				title:'删除成功',
				icon:"none"
			})
		}
	}
}